package com.gitee.feizns.quickstart.validation.validator;

import com.gitee.feizns.dynamic.reflect.Constructors;
import com.gitee.feizns.dynamic.stream.Streams;
import com.gitee.feizns.quickstart.validation.Validator;
import com.gitee.feizns.quickstart.validation.Verifiable;
import com.gitee.feizns.quickstart.validation.constraints.DynamicValidate;

import javax.validation.ConstraintValidatorContext;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 动态验证约束验证器
 * @author feizns
 * @since 2023/04/17
 */
public class DynamicValidateConstraintValidator extends AbstractConstraintValidator<DynamicValidate, Object> {

    /**
     * 可验证对象
     */
    private Set<Validator> verifiableSet;

    @Override
    public void initialize(DynamicValidate constraintAnnotation) {
        super.initialize(constraintAnnotation);
        verifiableSet = Streams.of(constraintAnnotation.value()).map(Constructors::newInstance).map(val -> (Validator) val).collect(Collectors.toSet());
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        boolean result = true;
        if ( value instanceof Verifiable )
            result = ((Verifiable) value).validate();
        return result && verifiableSet.stream().allMatch(verifiable -> verifiable.validate(value));
    }

}
